/*
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.demo.notepad1;

import android.app.ListActivity;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;


public class Notepadv1 extends ListActivity {
    public static final int INSERT_ID = Menu.FIRST;
	
	private int mNoteNumber = 1;
	private int currentRowId = 0;
	
    private NotesDbAdapter mDbHelper;
    private static final Object STRIKE_SPAN = new StrikethroughSpan();
    private OnTouchListener onTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if(v!=null && v instanceof EditText) {
				String text = ((EditText)v).getText().toString();
				//setze die aktuell ausgewaehlte zeile als holder, damit man den db eintrag updaten kann
				currentRowId = mDbHelper.findNoteRowIdByTitle(text);
			}
        	Log.i("DEBUG", "onTouch");
			return false;
		}
	};
	
	private OnKeyListener onKeyListener = new OnKeyListener() {
		
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			if(v!=null && v instanceof EditText && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
				//enter pressed in text view
				String newText = ((EditText)v).getText().toString();
				newText = newText.trim();
				mDbHelper.updateNote(currentRowId, newText, "notclicked");	
				v.clearFocus();
				fillData();
			}
			return false;
		}
	};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notepad_list);
        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();
        fillData();
    }
    
    public void cbClicked(View v) {
    	LinearLayout ll = (LinearLayout) v.getParent();
    	try {
    		//wurde gechecked?
        	EditText editText = (EditText) ll.getChildAt(1);
    		boolean checked = ((CheckBox)v).isChecked();
    		String textOnView = editText.getText().toString();
    		int rowId = mDbHelper.findNoteRowIdByTitle(textOnView);
    		if(checked) {
    			Utils.setStrikedText((StrikethroughSpan)STRIKE_SPAN, editText, null);
    			mDbHelper.updateNote(rowId, textOnView, "clicked");
    		} 
    		else {
    			Utils.removeStrikedText((StrikethroughSpan)STRIKE_SPAN, editText, null);
    			mDbHelper.updateNote(rowId, textOnView, "notclicked");            	
    		}    		
    	}catch(Exception e) {
        	Log.i("DEBUG", "bummm ! "+e);
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0,INSERT_ID, 0, R.string.menu_insert);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case INSERT_ID:
			createNote();
			return true;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
    
    private void createNote() {
    	String noteName = "Your Task "+mNoteNumber++;
    	mDbHelper.createNote(noteName, "notclicked");
    	fillData();
    }
    
    private void fillData() {
    	try {
        	Cursor c = mDbHelper.fetchAllNotes();
        	startManagingCursor(c);    	
        	String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
        	int[] to = new int[] { R.id.text1 };
        	SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
            adapter.setViewBinder(new ViewBinder() {
                
                @Override
                public boolean setViewValue(View view, Cursor theCursor, int column) {
                    String aColumnString = theCursor.getString(1);
                    String bColumnString = theCursor.getString(2);                    
                    EditText editText = (EditText)view;
                    LinearLayout ll = (LinearLayout) view.getParent();
                    CheckBox cb = (CheckBox) ll.getChildAt(0);
                    if(bColumnString.equals("clicked")) {
                    	Utils.setStrikedText((StrikethroughSpan)STRIKE_SPAN, editText, aColumnString);
                    	cb.setChecked(true);
                    }
                    else {
            			Utils.removeStrikedText((StrikethroughSpan)STRIKE_SPAN, editText, aColumnString);
                    	cb.setChecked(false);            			
                    }                    	
                    editText.setOnTouchListener(onTouchListener);
                    editText.setOnKeyListener(onKeyListener);
                    return true;
                }
            });

            this.setListAdapter(adapter);
        }
    	catch(Exception e) {
    		Log.i("DEBUG", "BUMM"+ e);
    	}
    }

}
